<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input placeholder="设备SN" v-model="listQuery.sn" style="width: 200px;" class="filter-item" />
      <el-date-picker class="filter-item"
        v-model="listQuery.agingDate"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
        :picker-options="pickerOptions">
      </el-date-picker>

      <el-button class="filter-item search-btn" type="success" icon="el-icon-search"
        @click="onSearch">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;"
        type="primary" icon="el-icon-magic-stick"
        @click="onScan">
        扫码
      </el-button>
    </div>

    <el-table v-loading="listLoading"
              :row-class-name="deviceRowClassName"
              :data="list" border fit highlight-current-row style="width: 100%" >
      <el-table-column type="expand" fixed>
        <template slot-scope="{row}">
          <el-form label-position="left">
            <el-form-item label="设备型号">
              <span>{{ row.model }}</span>
            </el-form-item>
            <el-form-item label="开始时间">
              <span>{{ row.agingStartTime }}</span>
            </el-form-item>
            <el-form-item label="结束时间">
              <span>{{ row.agingEndTime }}</span>
            </el-form-item>
            <el-form-item label="不良代码">
              <span>{{ row.errorCode }}</span>
            </el-form-item>
            <el-form-item label="老化时间">
              <span>{{ row.ci }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column type="index" width="50" align="center"/>


      <el-table-column width="150" label="设备SN" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sn }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" label="通道码" align="center">
        <template slot-scope="{row}">
          <span>{{ row.channel }}</span>
        </template>
      </el-table-column>

      <el-table-column width="80" label="老化次数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.agingTimes }}</span>
        </template>
      </el-table-column>

      <el-table-column width="80px" label="设定电压" align="center">
        <template slot-scope="{row}">
          <span>{{ row.presetVoltage }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" label="设定电流" align="center">
        <template slot-scope="{row}">
          <span>{{ row.presetCurrent }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" label="设定时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.presetDuration ? (row.presetDuration / 3600) : '' }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="添加时间">
        <template slot-scope="{row}">
          <span>{{ row.created }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120" label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status | statusFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120" label="老化结果" align="center">
        <template slot-scope="{row}">
          <span>{{ row.agingResult == 1 ? '正常' : ( row.result == 2 ? '异常' : '-') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="200px" fixed="right">
        <template slot-scope="{row}">
          <el-button
            v-if="!isOperator"
            :disabled="row.status != 1" type="primary"
            size="small" icon="el-icon-edit" @click="onConfig(row)">
            配置
          </el-button>

          <el-button type="danger" size="small" icon="el-icon-delete" @click="onDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList" />

    <el-dialog
      title="配置"
      :visible.sync="dialogVisible"
      width="300px"
      >
      <el-form ref="form" :model="configForm" label-width="150px">
        <el-form-item label="设定时间（小时）">
          <el-input v-model="configForm.presetDuration"></el-input>
        </el-form-item>
        <el-form-item label="设定电压（V）">
          <el-input v-model="configForm.presetVoltage"></el-input>
        </el-form-item>
        <el-form-item label="设定电流（A）">
          <el-input v-model="configForm.presetCurrent"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onConfirmConfig">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="scanDialogVisible" width="50%"
      :close-on-click-modal="false">

      <div style="width:100%;color:#E6A23C;font-size:30px;text-align:center;font-weight:bold;margin-bottom: 20px;">
        正在扫码中，请勿关闭窗口
      </div>
      <el-form :model="deviceForm" style="text-align:center;">
        <el-row :gutter="10">
        <el-col :md="10">
        <el-form-item>
          <el-input placeholder="通道码"
            ref="channelBox"
            v-model="deviceForm.channel"
            tabindex="1"
            style="ime-mode:active"
                    @blur="onChannelBlur"
            @keypress.native="onChannelKeyPress"
            >
            <template slot="prepend">通道码：</template>
          </el-input>
        </el-form-item>
        </el-col>

        <el-col :md="10">
        <el-form-item>
          <el-input placeholder="设备SN"
            ref="snBox"
            v-model="deviceForm.sn"
            tabindex="2"
            @keypress.native="onSnKeyPress"
            >
            <template slot="prepend">设备号：</template>
          </el-input>
        </el-form-item>
        </el-col>
          <el-col :md="4" v-if="!isOperator">
            <el-button type="success" @click="generateSn">生成SN</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        ref="newDeviceTable"
        :data="newDevices"
        empty-text="-"
        :row-class-name="tableRowClassName"
        @selection-change="onSelectionChange"
        border fit style="width: 100%">
        <el-table-column type="index" width="50" align="center"/>

        <el-table-column type="selection" align="center">
        </el-table-column>

        <el-table-column label="通道码" align="center">
          <template slot-scope="{row}">
            <span>{{ row.channel }}</span>
          </template>
        </el-table-column>

        <el-table-column label="设备SN" align="center">
          <template slot-scope="{row}">
            <span>{{ row.sn }}</span>
          </template>
        </el-table-column>

        <el-table-column width="120" label="已老化次数" align="center">
          <template slot-scope="{row}">
            <span>{{ row.agingTimes }}</span>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="scanDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onAdd">添加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDeviceBySn,
  getDevices,
  configDevice,
  deleteDevice,
  batchAdd,
  getDeviceByChannel
} from '@/api/device'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getNextSn } from '@/utils/auth'

export default {
  name: 'Device',
  components: { Pagination },
  filters: {
  },
  data() {
    return {
      dialogVisible: false,
      scanDialogVisible: false,
      configForm: {
        id: null,
        voltage: '',
        current: '',
        time: ''
      },

      deviceForm: {
        channel: null,
        sn: null
      },

      devices: [],
      newDevices: [

      ],
      selectedRows: [

      ],
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        sn: null,
        agingDate: null,
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      date: null
    }
  },
  created() {
    this.getList()
  },

  computed: {
    isOperator() {
      let roles = this.$store.getters.roles;

      return (roles || []).some(role => {
        return (role == 'operator')
      })
    }
  },


  methods: {
    getList() {
      this._queryList()
    },

    deviceRowClassName({row, rowIndex}) {
      console.log(row.status)

      if (row.status == 1) {
        return 'new-device-row';
      }

      return '';
    },

    tableRowClassName({row, rowIndex}) {
      if (row.isDuplicated) {
        return 'warning-row';
      }

      if (row.agingTimes > 0) {
        return 'hilight-row';
      }

      return '';
    },

    onConfig(row) {
      this.configForm = {
        id: row.id,
        presetVoltage: row.presetVoltage,
        presetCurrent: row.presetCurrent,
        presetDuration: row.presetDuration ? parseInt(row.presetDuration / 3600) : ''
      }

      this.dialogVisible = true;
    },

    onConfirmConfig() {
      // 时间转化成秒
      let params = Object.assign({}, this.configForm)
      params.presetDuration = params.presetDuration * 3600

      configDevice(params).then(() => {
        this.$message({
          message: '修改配置成功！',
          type: 'success'
        })
      }).finally(() => {
        this.dialogVisible = false;

        this._queryList()
      })
    },

    onScan() {
      this.scanDialogVisible = true;

      this.$nextTick(() => {
        this.$refs.channelBox.focus();
      })
    },

    _queryList() {
      let agingStartTime = null
      let agingEndTime = null
      let d = this.listQuery.agingDate
      if (d && d.length > 0) {
        agingStartTime = d[0]
        agingEndTime = d[1]
      }

      let params = {
        page: this.listQuery.page,
        limit: this.listQuery.limit,
        sn: this.listQuery.sn,
        status: 1,
        agingStartTime: agingStartTime,
        agingEndTime: agingEndTime
      }

      this.listLoading = true
      getDevices(params).then(res => {
        this.list = res.data.data.data
        this.total = res.data.data.count
      }).finally(() => {
        this.listLoading = false
      })
    },

    onSearch() {
      this._queryList()
    },

    onChannelBlur(e) {
      if ((/^A0[1-4][0-3]\d$/.test(this.deviceForm.channel))||(this.deviceForm.channel == 'A8888')) {
        getDeviceByChannel(this.deviceForm.channel).then(res => {
          let existingDevice = res.data.data
          if (existingDevice) {
            this.$message({
              message: `通道上面已绑定了设备：${existingDevice.sn}`,
              type: 'warning'
            })

            this.deviceForm.channel = ''
            this.$refs.channelBox.focus();
          } else {
            this.$refs.snBox.focus();
          }
        })
      } else {  // channel 无效
        this.deviceForm.channel = ''
        this.$refs.channelBox.focus();
      }
    },

    onChannelKeyPress(e) {
      if (e.code == 'Enter') {
        if (!this.deviceForm.channel) return;

       // if (/^A0[1-4][0-3]\d$/.test(this.deviceForm.channel)) {
        if ((/^A0[1-4][0-3]\d$/.test(this.deviceForm.channel))||(this.deviceForm.channel == 'A8888')) {
          getDeviceByChannel(this.deviceForm.channel).then(res => {
            let existingDevice = res.data.data
            if (existingDevice) {
              this.$message({
                message: `通道上面已绑定了设备：${existingDevice.sn}`,
                type: 'warning'
              })

              this.deviceForm.channel = ''
              // this.$refs.channelBox.focus();
            } else {
              this.$refs.snBox.focus();
            }
          })
        } else {
          this.deviceForm.channel = ''
        }
      }
    },

    onSnKeyPress(e) {
      if (e.code != 'Enter') {
        return;
      } else {
        if (!this.deviceForm.sn) return;

        if ((this.deviceForm.sn || '').length != 15) {
          this.$message({
            message: `SN错误：${this.deviceForm.sn}`,
            type: 'warning'
          })
          //this.deviceForm.channel = ''
          this.deviceForm.sn = ''
          //this.$refs.channelBox.focus();

          return
        }
      }

      // 只查询有过完整老化记录的设备
      getDeviceBySn(this.deviceForm.sn).then(res => {
        let existingDevice = res.data.data
        let newDevice = {
          channel: this.deviceForm.channel,
          sn: this.deviceForm.sn,
          agingTimes: 0
        }

        if (existingDevice) {
          newDevice.agingTimes = existingDevice.agingTimes
        }

        // channel相同的，后面的覆盖前面的
        let duplicated = this.newDevices.findIndex(d => {
          return d.channel == newDevice.channel
        })
        if (duplicated >= 0) {
          this.newDevices.splice(duplicated, 1)
        }

        // SN相同的，每一条都要高亮显示
        let snDuplicated = this.newDevices.findIndex(d => {
          return d.sn == newDevice.sn
        })

        if (snDuplicated >= 0) {
          this.newDevices.forEach(d => {
            if (d.sn == newDevice.sn) {
              d.isDuplicated = true
            }
          })

          newDevice.isDuplicated = true
        }

        this.newDevices.push(newDevice)
        this.$refs.newDeviceTable.toggleRowSelection(newDevice);

      }).finally(() => {
        this.deviceForm.sn = '';
        this.deviceForm.channel = '';
        this.$refs.channelBox.focus();
      });
    },

    onSelectionChange(rows) {
      this.selectedRows = rows;
    },

    generateSn() {
      let sn = getNextSn();

      this.deviceForm.sn = sn;
      this.$refs.snBox.focus();
    },

    onAdd() {
      if (!this.selectedRows || this.selectedRows.length == 0) {
        return
      }


      // 将老化次数都加一
      // 老化完成以后次数在+1 此处不加
      // this.selectedRows.forEach(d => d.agingTimes++)
      //console.log(this.selectedRows)
      //this.selectedRows.splice(0,1);/
       for(let i = 0 ;i<this.selectedRows.length;i++){
        if(this.selectedRows[i].channel == 'A8888'){
          this.selectedRows.splice(i,1);
        }
       }

      batchAdd(this.selectedRows).then(res => {
        this.$message({
            message: `添加成功！`,
            type: 'success'
          })

        this.newDevices = []
        this.selectedRows = []
      }).finally(() => {
        this._queryList()

      })

      this.scanDialogVisible = false
    },

    onDelete(row) {
      this.$confirm('确认要删除？').then(() => {
        deleteDevice(row.id).then(() => {
          this.$message({
            message: '删除成功！',
            type: 'success'
          })

          this._queryList()
        });
      })
    }
  }
}
</script>

<style>
  .el-table .warning-row {
    background: red;
  }

  .el-table .hilight-row {
    background: yellow;
  }
  body .el-table th.gutter {
    display: table-cell !important
}
</style>
